package be.vdab.servlets;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.vdab.dao.PizzaDAO;
import be.vdab.entities.Pizza;
import be.vdab.util.RequestStatistiek;

/**
 * Servlet implementation class PizzaServlet
 */
@WebServlet("/menu/pizzas.htm")
public class PizzaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String VIEW = "/WEB-INF/JSP/pizzas.jsp";
	private final RequestStatistiek requestStatistiek = new RequestStatistiek(); 
	private final PizzaDAO  pizzaDAO = new PizzaDAO(); 
    
    public PizzaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 	requestStatistiek.voegRequestToe(request);
	    request.setAttribute("pizzas", pizzaDAO.findAll());
	    request.setAttribute("sterren", 5);
	    
	    Collection<Pizza> pizzas = pizzaDAO.findAll();
	    String pizzaFotosPad = this.getServletContext().getRealPath("/pizzafotos");
	    Set<Long> pizzaNummersMetFoto = new HashSet<>();
	    for (Pizza pizza : pizzas) { 
		    File file = new File(pizzaFotosPad + "/" + pizza.getNummer() + ".jpg");
		    if (file.exists()) {   // is er foto voor deze pizza ?
		    	pizzaNummersMetFoto.add(pizza.getNummer());
		    }
	    }
	    
	    request.setAttribute("pizzas", pizzas);
	    request.setAttribute("pizzaNummersMetFoto", pizzaNummersMetFoto);

	    RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
	    dispatcher.forward(request, response);
	}

	
}
